package q15_threeSum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution_2 {
    public static void main(String[] args) {
        List<List<Integer>> lists = threeSum(new int[]{0,0,0});
        for (List<Integer> list : lists) {
            System.out.println(list);
        }

    }

    public static List<List<Integer>> threeSum(int[] nums) {
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if(len < 3){
            return res;
        }

        // 排序实现
        Arrays.sort(nums);

        for (int i = 0; i < len; i++) {

            if (nums[i] > 0) {
                break;
            }

            if((i != 0)&&(nums[i] == nums[i - 1])){
                continue;
            }

            int p2 = i + 1;
            int p3 = len - 1;

            while(p2 < p3){
                if(nums[i] + nums[p2] + nums[p3] > 0){
                    p3--;
                }else if(nums[i] + nums[p2] + nums[p3] < 0){
                    p2++;
                }else if(nums[i] + nums[p2] + nums[p3] == 0){
                    res.add(new ArrayList<>(List.of(nums[i] , nums[p2] , nums[p3])));
                    p2++;
                    p3--;
                    while((nums[p2] == nums[p2 - 1]) && (p2 < p3)){
                        p2++;
                    }
                    while((nums[p3] == nums[p3 + 1]) && (p2 < p3)){
                        p3--;
                    }
                }

            }

        }
        return res;
    }





}
